package com.szxy.service.impl;

import com.szxy.mapper.StorageTblExample;
import com.szxy.mapper.StorageTblMapper;
import com.szxy.pojo.StorageTbl;
import com.szxy.service.StorageService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: zwz
 * @Date:2020/7/15 17:04
 * @Description:com.szxy.service.impl
 * @Version:1.0
 **/
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageTblMapper storageTblMapper;

    private static final Logger logger = LoggerFactory.getLogger(StorageServiceImpl.class);

    @Transactional
    @Override
    public void reduceInventory(String productName, int count) {
        logger.info("商品{}， 容量为{}， 开始扣库存 ...", productName, count);
        String xid = RootContext.getXID();
        System.out.println("全局事务 xid = " + xid);
        // 1. 查询库存容量
        StorageTblExample example = new StorageTblExample();
        StorageTblExample.Criteria criteria = example.createCriteria();
        criteria.andCommodityCodeEqualTo(productName);
        List<StorageTbl> storageList = this.storageTblMapper.selectByExample(example);
        if(storageList == null  || storageList.isEmpty()) {
            throw new IllegalArgumentException("该商品不存在 ...");
        }
        StorageTbl storage = storageList.get(0);
        // 获取商品库存数量
        Integer storageCount = storage.getCount();
        if(storageCount <= 0) {
            throw new RuntimeException("该商品无库存");
        }
        if(storageCount < count) {
            throw new RuntimeException("该商品库存不足");
        }

        if ("HUAWEI_001".equals(productName)) {
            throw new RuntimeException("不想成功！");
        }

        // 2.若存在该商品，则进行扣减库存操作
        // 扣库存
        int newStoragecount = storageCount - count;
        storage.setCount(newStoragecount);
        // 更新
        this.storageTblMapper.updateByPrimaryKeySelective(storage);
        logger.info("商品{}， 现在容量为 {}， 扣库存成功 ...", productName, newStoragecount);

    }
}
